﻿using Quartz;
using Quartz.Impl;
using System;
using System.Threading.Tasks;

namespace ZLink.Elc.WinService.App.Quartz
{
    public class QuartzManagerAsync
    {
        //调度程序的工厂的接口中 实例一个具体的调度方法
        private static readonly ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
        //JOb群组名
        private const string JOB_GROUP_NAME = "JOBGROUP_NAME";
        //触发器群
        private const string TRIGGER_GROUP_NAME = "TRIGGERGROUP_NAME";


        /// <summary>
        /// 添加一个定时任务，使用默认的任务组名，触发器名，触发器组名
        /// </summary>
        /// <param name="pStrJobName">任务名</param>
        /// <param name="pStrCronExpress">触发器表达式</param>
        public static async Task AddJobAsync<T>(string pStrJobName, string pStrCronExpress) where T : class,IJob
        {
            try
            {
                //接口中获取调度工厂的  GetScheduler()  方法
                var sched = await schedulerFactory.GetScheduler();
                //创建任务
                var job = JobBuilder.Create<T>().WithIdentity(pStrJobName, JOB_GROUP_NAME).Build();
                //创建触发器
                var trigger = TriggerBuilder.Create()
                    .WithIdentity(pStrJobName, TRIGGER_GROUP_NAME)
                    .WithCronSchedule(pStrCronExpress)
                    .Build();

                await sched.ScheduleJob(job, trigger);
                await sched.Start();
            }
            catch (Exception e)
            {

                throw new Exception(e.Message);
            }
        }


        /// <summary>
        /// 移除一个任务(使用默认的任务组名，触发器名，触发器组名)
        /// </summary>
        /// <param name="pStrJobName"></param>
        public static async Task RemoveJobAsync(string pStrJobName)
        {
            try
            {
                var sched = await schedulerFactory.GetScheduler();
                var jobkey = new JobKey(pStrJobName);
                var triggerKey = new TriggerKey(pStrJobName, TRIGGER_GROUP_NAME);

                //停止触发器
                await sched.PauseTrigger(triggerKey);
                //移除触发器
                await sched.UnscheduleJob(triggerKey);
                //删除任务
                await sched.DeleteJob(jobkey);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }


        /// <summary>
        /// 修改一个任务的触发时间(使用默认的任务组名，触发器名，触发器组名)
        /// </summary>
        /// <param name="pStrJobName">任务名</param>
        /// <param name="pStrCronExpress">触发器表达式</param>
        /// <param name="pDictionary"></param>
        public static async Task AddOrUpdateAsync<T>(string pStrJobName, string pStrCronExpress) where T : class,IJob
        {
            try
            {
                var sched = await schedulerFactory.GetScheduler();
                var triggerKey = new TriggerKey(pStrJobName, TRIGGER_GROUP_NAME);
                var trigger = sched.GetTrigger(triggerKey);
                if (trigger == null)
                {
                    return;
                }
                await RemoveJobAsync(pStrJobName);
                await AddJobAsync<T>(pStrJobName, pStrCronExpress);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }


        /// <summary>
        ///  开启所有定时任务
        /// </summary>
        public static async Task StartJobsAsync()
        {
            try
            {
                var sched = await schedulerFactory.GetScheduler();
                await sched.Start();
            }
            catch (Exception e)
            {

                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 关闭所有的定时任务
        /// </summary>
        public static async Task ShutdownJobsAsync()
        {
            try
            {
                var sched = await schedulerFactory.GetScheduler();
                if (!sched.IsShutdown)
                {
                    await sched.Shutdown();
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 恢复所有的任务
        /// </summary>
        public static async Task ResumeAllJobsAsync()
        {
            try
            {
                var sched = await schedulerFactory.GetScheduler();
                if (!sched.IsShutdown)
                {
                    await sched.ResumeAll();
                }
            }
            catch (Exception e)
            {

                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 暂停所有的作业
        /// </summary>
        public static async Task PauseAllJobsAsync()
        {
            try
            {
                var sched = await schedulerFactory.GetScheduler();
                await sched.PauseAll();
            }
            catch (Exception e)
            {

                throw new Exception(e.Message);
            }
        }
    }



    //**********************使用方法********************************//

    //class MyJob : IJob
    //{
    //    public Task Execute(IJobExecutionContext context)
    //    {
    //        return Task.Run(() =>
    //        {
    //            Console.WriteLine(DateTime.Now.ToString());
    //        });
    //    }
    //}

    //QuartzManagerAsync.AddJob<MyJob>("myjob", "*/1 * * * * ?");


}